/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
	AppRegistry,
	StyleSheet,
	Text,
	View,
	Image,
	ScrollView,
	TouchableHighlight,
	TouchableOpacity,
	ToolbarAndroid,
	Dimensions,
	ListView,
	RefreshControl,
	DeviceEventEmitter,
	Platform
} from 'react-native';


import {CachedImageBackground} from "react-native-img-cache";

import Common from '../../../component/common';
import ScreenUtils from '../../../component/ScreenUtils';
import Toast from 'react-native-root-toast';

import Detail from '../../home/detail';
import VarietySearch from '../../search/varietySearch';

export default class varietyGroup extends Component {
	constructor(props) {
		super(props);
		this.state = {
			tvSource: [],
			fileSource: [],
			programSource: [],
			showDeleteButton: this.props.showDeleteButton,
			rows: this.props.data.list,
			deleteStatus: false,
			classType: this.props.classType,
			showTitle: this.props.showTitle,
			showPagation: false,
			noTitle: false,
			deleteArr:[],
		};
		this.selectArr=[];
		this.openScroll=[]
		this.fetchData = this.fetchData.bind(this);
	}
	componentWillReceiveProps(nextProps) {
		//alert(nextProps);
		if(parseInt(nextProps.classType) == -1 && nextProps.data.list != this.state.rows) {
			
			this.fetchData(nextProps.data.list);
			this.setState({
				rows: nextProps.data.list,
				deleteArr:this.selectArr
			})
			
		}
		if(this.openScroll.length>0){
	      this.openScroll.map((item,key)=>{
	          item.scrollTo({ x: 0, y: 0, animated: false });
	          this.openScroll=[]
	      })
	    }

	}

	componentDidMount() {
		this.fetchData(this.state.rows);
	}

	fetchData(data) {
		data.map((item, key) => {
			if(parseInt(item.type) == 1) {
				this.setState({
					programSource: item.list,
					programLength:item.list.length
				})
			} else if(parseInt(item.type) == 2) {
				this.setState({
					fileSource: item.list,
					fileLength:item.list.length
				})
			} else if(parseInt(item.type) == 3) {
				this.setState({
					tvSource: item.list,
					tvLength:item.list.length
				})
			}
			let cc =key;
		})

	}

	render() {
		return(
			<View>
	  		{
	  			this.state.rows.map((item,key)=>{
			  		if(parseInt(item.type)==1){
			  			return this.renderList(this.state.programSource,"综艺",1,key,this.state.programLength)
			  		}else if(parseInt(item.type)==2){
			  			return this.renderList(this.state.fileSource,"电影",2,key,this.state.fileLength)
			  		}else if(parseInt(item.type)==3){
			  			return this.renderList(this.state.tvSource,"电视剧",3,key,this.state.tvLength)
			  		}
		  		})
	  		}
  			</View>
		)

	}

	handleDelete(deleteType, rowIndex, entityId, target) {
		let formData = new FormData();
		formData.append("entityId", entityId);
		formData.append("userToken", this.props.userToken);
		Common.fetchData("POST", "/userCenter/collect/delete", formData, (responseData) => {
			let deleteGroup;
			if(deleteType == 1) {
				deleteGroup = this.state.program
			} else if(deleteType == 2) {
				deleteGroup = this.state.file
			} else if(deleteType == 3) {
				deleteGroup = this.state.tv
			}
			this.selectArr.push(entityId);
			this.setState({
				deleteArr:this.selectArr
			});
			//this.forceUpdate();

			//alert(this.state.deleteArr)
			// let arr = JSON.parse(JSON.stringify(deleteGroup));
			// arr.splice(rowIndex, 1);
			if(deleteType == 1) {
				this.setState({
					programLength:this.state.programLength-1,
				});
			}else if(deleteType == 2) {
				this.setState({
					fileLength:this.state.fileLength-1,
				});
			} else if(deleteType == 3) {
				this.setState({
					tvLength:this.state.tvLength-1,
				});
			}
			target.scrollTo({ x: 0, y: 0, animated: false });
			// if(arr.length <= 0) {
			// 	this.setState({
			// 		noDataType: deleteType,
			// 		noTitle: true,
			// 	})
			// }
			// //alert("aa:"+arr.length+"cc:"+rowIndex)
			// if(arr.length > 0 && arr.length != rowIndex) {
			// 	target.scrollTo({ x: 0, y: 0, animated: false });
			// }
			//DeviceEventEmitter.emit("dealCollection", this.state.classType);

			Toast.show("删除成功", {
				duration: 1000,
				position: Toast.positions.CENTER,
				shadow: true,
				animation: true,
				hideOnPress: true,
				delay: 0
			})
		}, () => {
			Toast.show("删除失败", {
				duration: 1000,
				position: Toast.positions.CENTER,
				shadow: true,
				animation: true,
				hideOnPress: true,
				delay: 0
			})
		}, () => {
			Toast.show("网络错误", {
				duration: 1000,
				position: Toast.positions.CENTER,
				shadow: true,
				animation: true,
				hideOnPress: true,
				delay: 0
			})
		});
	}

	renderList(data, typeName,type,key,length) {
		let marginStyle = length>0 ? {
			marginTop:ScreenUtils.scaleSize(10) ,
			borderTopWidth:1,
		} : {
			
		}
		return(
			<View key={key} style={styles.collectionVariety}>
				{
					 
				length>0 ?	<Text style={styles.collectionCategory}>
					      		<Text>{typeName}</Text>
					      	</Text> : null
				}

	      		<View style={[styles.Item,marginStyle]}>
					{
						data.map((item,key)=>{
							return this.renderVariety(item,key);
						})
					} 
				</View>
				<View style={{marginTop:-ScreenUtils.scaleSize(14)}}></View>
			</View>
		)
	}
	

	updown = (data) => {
		var updown = {};
		// var data = data?parseInt(data):0;
		if(data > 0) {
			updown.change = data;
			updown.icon = require('../../../images/up.png');
		} else if(data < 0) {
			updown.change = -data;
			updown.icon = require('../../../images/down.png');
		} else {
			updown.change = "";
			updown.icon = require('../../../images/still.png');
		}
		return updown;
	};

	showDeleteButton(ev, target) {
		if(this.startLocation > this.moveLocation) {
			target.scrollToEnd({ animated: true });
			this.openScroll.push(target)
		} else {
			target.scrollTo({ x: 0, y: 0, animated: true });
		}
	}

	renderVariety(data, rowID) {
		var _scrollView: ScrollView;
		var updown = this.updown(data.rankingChanged);
		var mydata = Common.keyWordHighlight(data.title);
		var Vheight = ScreenUtils.scaleSize(200);
		var vMarginBottom=ScreenUtils.scaleSize(14);
		this.state.deleteArr.map((item,key)=>{
			if(item==data.id){
				Vheight=0;
				vMarginBottom=0;
			}
		})
		return(
			<ScrollView
		      	horizontal = {true}
		      	showsHorizontalScrollIndicator = {false}
		      	ref={(scrollView) => { 
		      		_scrollView = scrollView; 
		      	}}
		      	contentContainerStyle={{marginBottom:vMarginBottom,height:Vheight,overflow:"hidden"}}
		      	onTouchStart={(event)=>{
		      		this.startLocation=event.nativeEvent.pageX
		      	}}
		      	onTouchMove={(event)=>{
		      		this.moveLocation=event.nativeEvent.pageX
		      	}}
		      	onScrollEndDrag={(event)=>{
		      		 this.showDeleteButton(event,_scrollView);
		      	}}
		      	key={rowID}
		      	bounces={false}
		    >
		      <TouchableHighlight underlayColor="#fafafa" delayPressIn={100} style ={styles.vItemContainer}
		      	onPress={() => Common.onForward(this.props.chageThis,Detail,data.type,data.id)}>
		      	<View style ={{flex:1,flexDirection:"row"}} >
			      	<View style={styles.vDescription}>
						<View style={[styles.vDesImgWrap,{
							marginLeft:ScreenUtils.scaleSize(20),
						}]}>
							{
								data.mainPicPath ? 
									<CachedImageBackground 
										style={styles.vDesImg} 
										source={{uri: data.mainPicPath }}
									/>	: <View style={[styles.vDesImgWrap,{borderWidth:1,borderColor:"#ededed"}]}><Text style={styles.noImg}>暂无图片</Text></View>
							}
						</View>
						<View style={styles.vDesInfo}>
							<Text style={styles.vDesTitle} numberOfLines ={2}>
								{
									!this.props.search ? <Text>{data.title}</Text>:
									<Text>
									{
									    mydata.map((item,i)=>{
									        if(item.hightLight){
									          	return(
									          		<Text key={i} style={{color:"red"}}>{item.data}</Text>
									          	)
									        }else{
									          	return(
									          		<Text key={i}>{item.data}</Text>
									          	)
									        }
									    })
								    }
									</Text>
								}
							
							</Text>
							{
								data.programTypeList ?
									<View style={styles.vDesCategory}>
										{
											 data.programTypeList.map((item,i)=>{
												return <View style={styles.vDes}><Text key={i} style={styles.vDesCategoryItem}>{item.title}</Text></View>
											})
										}
									</View> : null
							}
						
							<View style={styles.varietyContent}>
								{
									typeof(data.ranking)!=='undefined'?
									<Text style={styles.vBillBoard}>榜单 <Text style={{color:"#ff5151",}}>No.{String(data.ranking)}</Text></Text> : null
								}
								
								{
									typeof(data.rankingChanged)!=='undefined' ? <Image style={{marginLeft:5,}} source = {updown.icon}/> : null
								}
							</View>
						</View>
		      		</View>
			      	<View style={styles.vIndex}>
			      		<Text style={styles.vIndexTitle}>报道指数</Text>
			      		<Text style={styles.vIndexNum}>{data.indexNumber ? String(parseFloat(data.indexNumber).toFixed(1)):"0.0"}</Text>
			      	</View>
			    </View>
		      </TouchableHighlight>
			    {
			      	this.state.showDeleteButton ?
				      (
				      	<TouchableOpacity 
				      		style={styles.deleteWrap} 
				      		onPress={()=>{
				      			this.handleDelete(data.type,rowID,data.id,_scrollView)
				      			}
				      		}
				      	>
					      <Text style={styles.deleteText}>删除</Text>
					    </TouchableOpacity>
				      ):null
			    }
		    </ScrollView>
		);
	}
}

const styles = StyleSheet.create({
	vItemContainer: {
		width: Dimensions.get('window').width,
		backgroundColor: "#fff",
		flexDirection: "row",
		height: ScreenUtils.scaleSize(200),
		borderBottomWidth: 1,
		borderColor: "#ebebeb",
		justifyContent: "center",
		paddingLeft: ScreenUtils.scaleSize(30),
		paddingRight: ScreenUtils.scaleSize(26),
	},
	vDescription: {
		flex: 1,
		height: ScreenUtils.scaleSize(200),
		flexDirection: "row",
		alignItems: "center",
	},
	collectionCategory: {
		paddingLeft: ScreenUtils.scaleSize(30),
		fontSize: ScreenUtils.scaleSize(24),
		color: "#939393",
		paddingTop: ScreenUtils.scaleSize(14),
	},
	vDesImgWrap: {
		width: ScreenUtils.scaleSize(110),
		height: ScreenUtils.scaleSize(152),
		justifyContent: "center",
		alignItems: "center",
	},
	noImg: {
		color: "#ededed",
		fontSize: ScreenUtils.scaleSize(20),
	},
	vDesImg: {
		width: ScreenUtils.scaleSize(110),
		height: ScreenUtils.scaleSize(152),
	},
	vDesInfo: {
		flex: 1,
		height: ScreenUtils.scaleSize(152),
		flexDirection: "column",
		justifyContent: "space-around",
		paddingLeft: ScreenUtils.scaleSize(26),
	},
	vDesTitle: {
		fontSize: ScreenUtils.scaleSize(34),
		color: "#000",
	},
	vDesCategory: {
		flexDirection: "row",
	},
	vDes:{
		borderWidth: 1,
		borderColor: "#ff5050",
		marginRight: 5,
		borderRadius: 2,
		paddingHorizontal: 5,
	},
	vDesCategoryItem: {
		fontSize: ScreenUtils.scaleSize(16),
		color: "#ff4545",
		
	},
	vBillBoard: {
		fontSize: ScreenUtils.scaleSize(20),
		color: "#000",
	},
	vIndex: {
		width: ScreenUtils.scaleSize(200),
		alignItems: "flex-end",
		justifyContent: "center",
		paddingRight: ScreenUtils.scaleSize(20),
	},
	vIndexTitle: {
		color: "#d7d7d7",
		fontSize: ScreenUtils.scaleSize(20),
	},
	varietyContent: {
		flexDirection: "row",
		alignItems: "center",
	},
	vIndexNum: {
		fontSize: ScreenUtils.scaleSize(60),
		color: "#ff4545",
	},
	deleteWrap: {
		width: ScreenUtils.scaleSize(132),
		backgroundColor: "#ff4545",
		justifyContent: "center",
		alignItems: "center",
		borderBottomWidth: 1,
		borderColor: "#ebebeb",
	},
	deleteText: {
		fontSize: ScreenUtils.scaleSize(26),
		color: "#fff",
	},
	Item: {
		borderColor: "#ededed",
	},
	showMore: {
		flex: 1,
		justifyContent: "center",
		alignItems: "center",
		height: ScreenUtils.scaleSize(78),
		backgroundColor: '#fff',
		borderBottomWidth: 1,
		borderColor: '#ebebeb',
		flexDirection: "row",
		marginTop: -ScreenUtils.scaleSize(14),
	},
	seperatorCell: {
		backgroundColor: "#f60",
		marginTop: -ScreenUtils.scaleSize(14),
		zIndex: -5,
	}
});